<?php
namespace app\admin\controller;
use app\admin\model\Wechat as WechatModel;
use app\admin\model\Setting as SettingModel;

/**
 * 公众号管理
 */
class Wechat extends Controller
{
    /**
     * 公众号信息
     */
    public function index()
    {
        $wechat = WechatModel::detail();
        return $this->fetch('index', compact('wechat'));
    }
	
	/**
     * 被关注回复设置
     */
    public function subscribe()
    {
        return $this->updateEvent('subscribe');
    }
	
	/**
     * 公众号菜单设置
     */
    public function menus()
    {
        return $this->updateEvent('menus');
    }

    /**
     * 跳转到扫码授权页面
     */
    public function auth()
    {
        $this->success('即将跳转到扫码授权页面',authUrl(1));
    }

    /**
     * 更新设置事件
     */
    private function updateEvent($key)
    {
        if (!$this->request->isAjax()) {
            $values = SettingModel::getItem($key);
        	if($key == 'menus'){
				$values = json_encode($values);
        	}
            return $this->fetch($key, compact('values'));
        }
		//全局判断
		if($err = checking()){
			return $this->renderError($err);
		}
		$wechat = WechatModel::detail();
		if(empty($wechat['app_id'])){
			return $this->renderError('还未绑定公众号');
		}
        $model = new SettingModel;
        if ($model->edit($key,$this->postData('data'))){
            return $this->renderSuccess('更新成功');
        }
        $error = $model->getError() ?: '更新失败';
		return $this->renderError($error);
    }
}
